
<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  value: { type: Array, default: () => [] }
})
const emit = defineEmits(['update:value', 'close'])

const treeData = ref([
  {
    key: 'sys',
    title: '系统管理',
    children: [
      { key: 'user', title: '用户管理' },
      { key: 'role', title: '角色管理' }
    ]
  },
  {
    key: 'data',
    title: '数据权限',
    children: [
      { key: 'export', title: '数据导出' },
      { key: 'import', title: '数据导入' }
    ]
  }
])

const checkedKeys = ref([])
const expandedKeys = ref(treeData.value.map(item => item.key)) // 默认展开所有父节点
const getCheckedNodes = () => {
  const flattenNodes = (nodes) => 
    nodes.flatMap(node => [node, ...(node.children ? flattenNodes(node.children) : [])])
  
  return flattenNodes(treeData.value)
    .filter(node => checkedKeys.value.includes(node.key))
}
watch(() => props.value, (newVal) => {
  checkedKeys.value = [...newVal]
}, { immediate: true })

const handleOk = () => {
  // emit('update:value', checkedKeys.value)
  emit('update:value', {
    keys: checkedKeys.value,
    nodes: getCheckedNodes()
  })
  emit('close')
}
</script>

<template>
  <a-modal
    title="授权"
    :visible="true"
    @cancel="$emit('close')"
    @ok="handleOk"
  >
    <a-tree
      v-model:checkedKeys="checkedKeys"
      :expanded-keys="expandedKeys"
      checkable
      :tree-data="treeData"
      :field-names="{ key: 'key', title: 'title' }"
    />
  </a-modal>
</template>
